package com.tqjc.work.step;

import com.tqjc.entity.Task;
import com.tqjc.entity.TaskApart;
import com.tqjc.exception.TaskRunningException;
import com.tqjc.service.impl.TaskApartServiceImpl;
import com.tqjc.service.impl.TaskServiceImpl;
import com.tqjc.system.core.util.SpringUtils;
import com.tqjc.utils.PlcOperator;
import com.tqjc.work.TaskCallback;
import com.tqjc.work.TaskStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;



@Slf4j
@Component
@Scope("prototype")
public class SplitFlowSuckStep extends TaskApart implements TaskCallback {

    @Resource
    PlcOperator plcOperator;

    @Resource
    TaskStatus taskStatus;


    public SplitFlowSuckStep() {
        this.setType("splitFlowSuck");
    }


    @Override
    public void onPreExecute() {
        try {
            log.info("开始执行步骤前置，{}", getType());
            setBeginTime(new Date());
            //设置工作状态
            /*WorkStatus status = taskStatus.getWorkStatusByCraneType(getCraneType());
            status.setNowStep(getType());
            status.setNowSteelNum(getTask().getSteelNum());
            taskStatus.setWorkStatusByCraneType(getCraneType(), status);*/
            log.info("步骤前置执行结束，{}", getType());
        } catch (Exception e) {
            e.printStackTrace();
            log.error(getType()+"前置出现异常",e);
        }
    }

    @Override
    public void onPostExecute() {
        try {
            log.info("开始执行步骤后置，{}", getType());
            setEndTime(new Date());

            //修改步骤状态
            /*WorkStatus status = taskStatus.getWorkStatusByCraneType(getCraneType());
            status.setNowStep("");
            status.setNowSteelNum("");
            taskStatus.setWorkStatusByCraneType(getCraneType(), status);*/

            getTask().setTaskStatus(1);
            SpringUtils.getBean(TaskServiceImpl.class).saveOrUpdate(getTask());
            SpringUtils.getBean(TaskApartServiceImpl.class).insert(this);
            log.info("步骤后置执行结束，{}", getType());

            //清除bean
            destroy();
        } catch (Exception e) {
            log.error(getType()+"后置出现异常",e);
            e.printStackTrace();
        }

    }


    @Override
    public void setTaskApartByTask(Task task) {
        this.setCallback(this);
        super.setTaskApartByTask(task);
    }


    @Override
    public void customAction() throws TaskRunningException {
        try {
            String steelNum= getTask().getSteelNos();
            this.setSteelId(steelNum);

            //写入任务坐标
            log.info("步骤{}写入PLC开始", getType());
            //TODO  一次性全部吸起
            /*plcOperator.writeValueByLabelAndCraneType(WorkConst.TARGET_CRANE_X, getBeginX().toString(), craneType);
            plcOperator.writeValueByLabelAndCraneType(WorkConst.TARGET_CRANE_Y, getBeginY().toString(), craneType);
            List<SteelPlate> steels=getTask().getSteels4Offline();
            Integer height=0;//如果是suck多块，z轴要加上（已吸钢板-1）和要吸钢板的厚度
            for(int i=1;i<steels.size();i++){ //吸第一块的高度在生成task时，就已经加到z轴上了，所以i从1开始；
                height+= steels.get(i).getThickness();
            }
            plcOperator.writeValueByLabelAndCraneType(WorkConst.TARGET_CRANE_Z, (getBeginZ()+height)+"", craneType);

            //写入任务类型
//            TODO:等待确认任务类型
            plcOperator.writeValueByLabelAndCraneType(WorkConst.STEP_TYPE, "1", craneType);

            //写入任务开始
            plcOperator.writeValueByLabelAndCraneType(WorkConst.STEP_START, "1", craneType);*/
            log.info("步骤{}写入PLC完成,等待任务完成", getType());
            boolean isFinished = false;
            while (!isFinished) {
                /*if (Boolean.parseBoolean(plcOperator.readValueByLabelAndCraneType(WorkConst.STEP_FINISH, craneType))) {
                    isFinished = true;
                    log.info("PLC反馈步骤{}完成", getType());
                }*/

                //TODO:测试使用
                Thread.sleep(5000);
                isFinished = true;
                Thread.sleep(500);
            }

        } catch (Exception e) {
            throw new TaskRunningException(e.getMessage(),null);
        }


    }


    @Override
    public void destroy() throws Exception {

    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }
}


